﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PSLib.Parsing.Common
{

    public enum SearchDirection
    {
        Forward,
        Backward,
    }

    public static class ListExtension
    {
        public static int LinearRangeSideSearch(this List<object> list, object item, int startPosition, SearchDirection direction, IComparer<object> comparer)
        {
            if (list == null || startPosition < 0 || startPosition >= list.Count || item == null || comparer == null) return -1;
            int currentIndex = startPosition;
            while (true)
            {
                int compareResult = comparer.Compare(list[currentIndex], item);

                if (direction == SearchDirection.Forward)
                {
                    if (compareResult > 0) return currentIndex;
                    currentIndex++;
                    if(currentIndex >= list.Count) return list.Count-1;
                }
                else
                {
                    if (compareResult < 0) return currentIndex;
                    currentIndex--;
                    if (currentIndex <= 0) return 0;
                }
            }
        }
    }
}
